<?php
namespace app\api\controller;

use app\BaseController;
use app\common\Kuaidi100;
use app\console\model\Config;
use app\model\MemberBrokerage;
use app\model\Order as SelfModel;
use app\model\Member;
use app\model\OrderGoods;
use app\model\OrderRefund;
use app\model\Shop;
use app\model\ShopStore;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cookie;
use think\Response;
use think\Request;
use think\facade\Db;

class Order extends Base
{


    public function initialize()
    {
        parent::initialize();
        $this->model = "\app\model\Order";
        $this->list_rows = 10;
        $this->index = ['id','member_id','member_mobile','date','time','name','mobile','order_number','status','shop_id','shop_title','shop_store_id','shop_store_title','coupon_id','total_price','price','create_time'];
        $this->all = ['id','member_id','member_mobile','date','time','name','mobile','order_number','status','shop_id','shop_title','shop_store_id','shop_store_title','coupon_id','total_price','price','create_time'];
        $this->my = ['id','member_id','member_mobile','date','time','name','mobile','order_number','status','shop_id','shop_title','shop_store_id','shop_store_title','coupon_id','total_price','price','create_time'];
        $this->view = ['id','member_id','member_mobile','date','time','name','mobile','order_number','status','shop_id','shop_title','shop_store_id','shop_store_title','coupon_id','total_price','price','create_time'];
        $this->msg = '预约订单';
        
        $this->status = [['status','=','1']];
    }


    public function index(Request $request)
    {
        $data = SelfModel::withSearch(array_keys($request->param), $request->param)

        ->order([ 'id' => 'desc'])
        ->paginate(6)->each(function ($item,$key){
            $item['type'] = $item['status'];

            });

        return json(['code' => 200, 'message' => '列表', 'orderList' => $data]);
    }

    public function all(Request $request)
    {
        $data = SelfModel::withSearch(array_keys($request->param), $request->param)
        ->where([['status', '=', 1]])
        ->order(['sort' => 'asc', 'id' => 'desc'])
        ->select();
        return json(['code' => 200, 'message' => '全部(无分页)', 'data' => $data]);
    }



    public function create(Request $request)
    {
         return json(['code' => 400, 'msg' => '温馨提示：系统临时调整,请稍后']);
        Db::startTrans();
        try {
            $data = $request->param;
//            writeLog(var_export($data,true));
            $goods = Db::name('cart')->orderField('id',[$request->cart_id],'desc')->where('type',$request->type)->where('member_id',$request->member_id)->select();
            $total_price = 0;
            $total_count = 0;
            $make_order_count = 0;

            foreach ($goods as &$v){
                $g = \app\model\Goods::where('id',$v['goods_id'])->find();

                $level_id = \app\model\Member::where('id',$v['member_id'])->value('level_id') ?? 0;

                $price = $g['price_'.$level_id];
                $v['price'] = $price;
                $total_price += $v['price']*$v['number'];
                $total_count += $v['number'];
                $make_order_count += \app\model\Goods::where('id',$v['goods_id'])->value('num')*$v['number'];
            }
            $address = \app\model\Address::where('id',$request->address_id)->find();
            $data['order_number'] = order_number();
            $data['type'] = 1;
            $data['total_price'] = $total_price;
            $data['total_count'] = $total_count;
            $data['make_order_count'] = $make_order_count;
            $data['address'] = $address['address'];
            $data['name'] = $address['name'];
            $data['mobile'] = $address['mobile'];
            $data['prov'] = $address['prov'];
            $data['city'] = $address['city'];
            $data['area'] = $address['area'];
            $goods_ids = Db::name('cart')->orderField('id',[$request->cart_id],'desc')->where('type',$request->type)->where('member_id',$request->member_id)->column('goods_id');
            $data['goods_data'] = implode(',',$goods_ids);
            writeLog($data);
            $order = SelfModel::create($data);

            foreach ($goods as $v2){
                $g = \app\model\Goods::where('id',$v2['goods_id'])->find();

                $level_id = \app\model\Member::where('id',$v2['member_id'])->value('level_id') ?? 0;

                $price = $g['price_'.$level_id];
                $single_pic = \app\model\Goods::where('id',$v2['goods_id'])->value('single_pic');
                $title = \app\model\Goods::where('id',$v2['goods_id'])->value('title');
                $number2 = $g['num'];
                OrderGoods::create(['order_id'=>$order['id'],'order_number'=>$order['order_number'],'title'=>$title,'goods_id'=>$v2['goods_id'],'number'=>$v2['number'],'number2'=>$number2,'price'=>$price,'single_pic'=>$single_pic]);
            }

            $pre = Config::where('varname', 'web_distribution')->value('varvalue');
            //MemberBrokerage::saveData($request->member_id, '0', '预约', '+', $request->total_price, $request->total_price * $pre, $ret['order_number']);
            Db::commit();
            if ($order) {
                return json(['code' => 200, 'msg' => '订单创建成功,请支付', 'data' => $order]);
            }
        } catch (\Exception $e) {
            DB::rollback();
            writeLog('end_'.$e->getMessage().'_end');
            return json(['code' => 400, 'msg' => $e->getMessage()]);
        }
    }




    function extend($obj, $obj2) {
        $vars = get_object_vars($obj2);
        foreach ($vars as $var => $value) {
            $obj->$var = $value;
        }
        return $obj;
    }

    public function update(Request $request)
    {
        $info = SelfModel::find($request->id);
        $ret = $info->save($this->param);
        if ($ret !== false) {
        return json(['code' => 200, 'message' => '修改成功']);
        }
        return json(['code' => 200, 'message' => '失败']);
    }


    public function destory(Request $request)
    {
        Db::startTrans();
        try {

            $order = SelfModel::where('id', '=', $request->id)->find();

            if($order['status'] != 1){
                return json(['code' => 400, 'message' => '当前不是待支付状态']);
            }
            if ($order['coupon_id'] > 0) {
                \app\model\MemberCoupon::where('id', $order['coupon_id'])->update(['status' => 1, 'usetime' => '']);

            }
            (new MemberBrokerage())->where('order_number',$order['order_number'])->delete();
            $ret = SelfModel::where('id', '=', $request->id)->update(['delete_time' => date('Y-m-d H:i:s')]);
            DB::commit();
            if ($ret) return json(['code' => 200, 'message' => '取消订单成功']);
            return json(['code' => 400, 'message' => '失败']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 400, 'message' => $e->getMessage()]);
        }
    }

    /*
     * 订单详情
     */
    public function view(Request $request)
    {
        $data = SelfModel::with(['OrderGoods'])->find($request->id);
        return json(['code' => 200, 'message' => '订单详情', 'data' => $data]);
    }


    /*
     * 我的订单
     */
    public function my(Request $request)
    {
        $data = SelfModel::withSearch(array_keys($request->param), $request->param)->with(['OrderGoods'])->order(['id'=>'desc'])->paginate(20);
        return json(['code' => 200, 'msg' => '我的订单', 'data' => $data]);
    }

    /*
     * 取消订单
     */
    public function cancel(Request $request)
    {
        $order = SelfModel::where('id', $request->id)->find();
        if ($order['status'] != 1) {
            return ['code' => 400, 'msg' => '当前不是待支付状态'];
        }
        $ret = SelfModel::where('id', $request->id)->update(['status' => -1]);
        return ['code' => 200, 'msg' => '订单取消成功'];
    }

    /*
     * 修改备注
     */
    public function update_remark(Request $request)
    {
        $order = SelfModel::where('order_number', $request->order_number)->find();
        $ret = SelfModel::where('id', $request->id)->update(['remark' =>$request->remark]);
        return ['code' => 200, 'msg' => '备注修改成功'];
    }
    /*
     * 确认收货
     */
    public function confirm_receive_goods(Request $request)
    {
        $order = SelfModel::where('id', $request->id)->find();
        if ($order['status'] != 3) {
            return ['code' => 400, 'msg' => '当前发货状态'];
        }
        $ret = SelfModel::where('id', $request->id)->update(['status' => 4]);
        return ['code' => 200, 'msg' => '确认收货成功'];
    }

    /*
     *快递查询
     */
    public function kuaidi(Request $request)
    {
        $res = Kuaidi100::check($request->express_code,$request->express_number,$request->mobile);
        return $res;
    }

    /*
     * 退款金额
     * 2已支付 代发货
     * 3已发货 带收货
     * 4已收货 完事
     * member_id
     * order_number
     * 缺少商品id
     */
    public function refund(Request $request)
    {
        Db::starttrans();
        try {
            $order = SelfModel::where('order_number', $request->order_number)->where('member_id', $request->member_id)->find();
            if (empty($order)) {
                return ['code' => 400, 'msg' => '订单不存在'];
            }
            if ($order['status'] > 10) {
                return ['code' => 400, 'msg' => '订单已经是退款状态'];
            }
            if ($order['status'] == 2) {
                $type = '退款';
                $status = 11;
            }
            if (in_array($order['status'], [3,4])) {
                $type = '退货';
                $status = 14;
            }
            if($order['pay_type'] == 3){
                return ['code' => 400, 'msg' => '积分抵扣,请等待'];
            }
            $order_refund = OrderRefund::where('order_number',$order['order_number'])->find();
            if(!empty($order_refund)){
                return ['code' => 400, 'msg' => '退款单已经申请过了,不要重复申请'];
            }
            OrderRefund::create([
                'order_number' => $order['order_number'],
                'refund_number' => order_number(),
                'total_price' => $order['total_price'],
                'refund_price' => $order['total_price'],
                'content' => $request->content,
                'type' => $type,
                'pay_type'=> $order['pay_type'],
                'audit_status' => 1
            ]);
            SelfModel::where('order_number', $order['order_number'])->update(['is_refund' => 2]);
            Db::commit();
            return ['code' => 200, 'msg' => '申请成功,等待审核'];
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => $e->getMessage()];
        }

    }


    public function my_refund(Request $request)
    {
       $data =  OrderRefund::where('member_id', $request->member_id)->select();
        return ['code' => 200, 'msg' => '我的退款单','data'=>$data];
    }




}
